/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.alibaba.fastjson.JSONArray;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.scene.domain.SafetyCheck;
import com.koron.scene.domain.SafetyCheckCondition;
import com.koron.scene.service.api.SafetyCheckService;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "safetyCheck", description = "安全检查接口")
@RestController
@RequestMapping("/safetyCheck")
public class SafetyCheckController {

    private final static Logger logger = LoggerFactory.getLogger(SafetyCheckController.class);
    @Autowired
    private SafetyCheckService service;

    @ApiOperation("保存安全检查表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id,新增不传，修改必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "projectName", value = "工程名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "checkDate", value = "检查日期", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "inspector", value = "检查人", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "inspectorName", value = "检查人名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "inspectedUnit", value = "被检查单位", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "inspectedUnitName", value = "被检查单位名称", required = true, dataType = "string", paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存安全检查表接口",businessModule = "安全检查", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                     @ApiIgnore SafetyCheck bean, @RequestParam String safetyCheckConditions) {
        MessageBean<Integer> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isEmpty(safetyCheckConditions)) {
            messageBean.setCode(BusinessCode.FAILURE.getCode());
            messageBean.setDescription("检查整改情况不能为空");
            return messageBean;
        }
        List<SafetyCheckCondition> safetyCheckConditionList = JSONArray.parseArray(safetyCheckConditions, SafetyCheckCondition.class);
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        return service.save(bean, safetyCheckConditionList, user);
    }

    @ApiOperation("删除安全检查表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除安全检查表",businessModule = "安全检查", businessManipulation = BusinessManipulation.DELETE)

    public MessageBean<Integer> delete(@RequestParam final String id, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.delete(id, user);
    }


    @ApiOperation("查询安全检查表详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.GET)
    public MessageBean<SafetyCheck> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<SafetyCheck> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.queryOne(id);
    }

    @ApiOperation("安全检查表列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "projectName", value = "工程名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始日期" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "截止日期" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public MessageBean<DataBean> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String corpCode,
                                                   @RequestParam(required = false) final String projectName,
                                                   @RequestParam(required = false) final String startDate,
                                                   @RequestParam(required = false) final String endDate,
                                                   @RequestParam Integer page,
                                                   @RequestParam Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean> msg = service.list(corpCode, projectName, startDate, endDate, start, pageSize);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("获取安全检查表检查内容详情接口")
    @RequestMapping(value = "/getSafetyCheckCondition.htm", method = RequestMethod.GET)
    public MessageBean<List> getSafetyCheckCondition(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<List> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        MessageBean<List> msg = service.getSafetyCheckCondition();
        return msg;
    }

    @ApiOperation("安全检查表导出")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/exports.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exports(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            return null;
        }
        MessageBean<SafetyCheck> msg = service.queryOne(id);
        if (null == msg.getData()) {
            return null;
        }
        SafetyCheck safetyCheck = msg.getData();
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        safetyCheck.setCheckDateStr(simpleDateFormat.format(safetyCheck.getCheckDate()));
        map.put("data", safetyCheck);
        File targetFile = new File("static/excel/safetyCheck.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/safetyCheck.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile( "安全检查表", targetFile, "safetyCheck.btl", map);
    }
}
